<?php

namespace Backend\Controllers;

use Models\Wx;
use Models\WxAreply;
use Models\WxImg;
use Models\WxImgmulti;
use Models\WxKeyword;
use Models\WxMenu;
use Models\WxText;
use \Wechat;

class AppwxController extends BaseController
{
    public function beforeExecuteRoute($dispatcher)
    {
        parent::beforeExecuteRoute($dispatcher);
        $Cuser = $this->Cuser;
        $wxc = Wx::findFirstByuid($Cuser->uid);
        if (!$wxc) {
            $this->flash->warning("<a href='admin/config/wx'>请先点击这里进行微信配置，公共配置->微信配置</a>");
        }
        $this->view->setVar("wxc", $wxc->uid);
    }

    public function indexAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $this->view->setVar('url', $this->config->host . "/wechat/index/" . $token);
        $this->view->setVar('token', $token);
        $this->view->imgcount = WxKeyword::count("token='" . $token . "' AND module='Img'");
        $this->view->textcount = WxKeyword::count("token='" . $token . "' AND module='Text'");
        $this->view->count = WxImg::sum(array("token='" . $token . "'", 'column' => 'click'));

    }

    public function dashboardAction()
    {
//        $Cuser = $this->Cuser;
//        $wx = Wx::findFirstByuid($Cuser->uid);
//        include $this->config->application->libDir . "wechat.class.php";
//        $options = array(
//            'token' =>"fecfbf32be4a3f623686bcfb00c808ec",                     //$wx->token, //填写你设定的key
//            'appid' =>"wxab5b546d18195eac",                                          //$wx->appid, //填写高级调用功能的app id
//            'appsecret' =>"89417656b827eaf073c764ffbedd7761",                                   //$wx->appsecret, //填写高级调用功能的密钥
//            'encodingaeskey' => 'XYP0op08zcq4YDWa4td283Witvb0Q4TgVLMpunuGyXq', //填写加密用的EncodingAESKey
//        );
//
//        $weObj = new Wechat($options); //创建实例对象
//        //TODO：调用$weObj各实例方法
////        $weObj->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
//        $date = $weObj->getDatacube('user',"summary","2015-03-27");
//        print_r($date);
//        echo 1;
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token=$wx->token;
        $this->view->imgcount = WxKeyword::count("token='" . $token . "' AND module='Img'");
        $this->view->textcount = WxKeyword::count("token='" . $token . "' AND module='Text'");
        $this->view->count = WxImg::sum(array("token='" . $token . "'", 'column' => 'click'));

    }

    public function replyAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $reply = WxAreply::findFirstBytoken($token);
        if ($reply) {
            if ($this->request->isPost() == true) {
                $reply->updatetime = date("Y-m-d H:i:s", strtotime("now"));
                $reply->check = $this->request->getPost("check");
                if ($reply->update($this->request->getPost())) {
                    $this->flash->warning("更新成功");
                } else {
                    $this->flash->warning("更新失败");
                }
            }
        } else {
            if ($this->request->isPost() == true) {
                $reply = new WxAreply();
                $reply->createtime = date("Y-m-d H:i:s", strtotime("now"));
                $reply->updatetime = date("Y-m-d H:i:s", strtotime("now"));
                $reply->token = $token;
                if ($reply->create($this->request->getPost())) {
                    $this->flash->warning("保存成功");
                } else {
                    $this->flash->warning("保存失败");
                }
            }
        }
        $this->view->setVar("reply", $reply);
    }

    public function fansAction()
    {

    }

    public function exampleAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        echo "url:http://yzzdev.1yizu.com/wechat/index/" . $token . "<br>";
        echo "token:" . $token;
    }

    public function textAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $wxtext = WxText::findBytoken($token);
        $this->view->setVar("wxtext", $wxtext);
    }

    public function addtextAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        if ($this->request->isPost() == true) {
            $wxtext = new WxText();
            $wxtext->token = $token;
            $wxtext->type = 1;
            $wxtext->click = 0;
            $wxtext->createtime = date("Y-m-d H:i:s", strtotime("now"));
            $wxtext->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($wxtext->create($this->request->getPost())) {
                $this->flash->warning("保存成功");
                $keyword = new WxKeyword();
                $keyword->pid = $wxtext->id;
                $keyword->token = $token;
                $keyword->module = "Text";
                $keyword->create($this->request->getPost());
            } else {
                $this->flash->warning("保存失败");
            }
        }
    }

    public function edittextAction($id)
    {
        if ($this->request->isPost() == true) {
            $wxtext = WxText::findFirstByid($id);
            $wxtext->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($wxtext->update($this->request->getPost())) {
                $this->flash->warning("更新成功");
                $keyword = WxKeyword::findFirst("pid='" . $id . "' AND module='Text'");
                $keyword->update($this->request->getPost());
            } else {
                $this->flash->warning("更新失败");
            }
        }
        $wxtext = WxText::findFirstByid($id);
        $this->view->setVar("wxtext", $wxtext);
    }

    public function deltextAction($id)
    {
        $this->view->disable();
        $wxtext = WxText::findFirstByid($id);
        $keyword = WxKeyword::findFirst("module='Text' AND pid='" . $id . "'");
        if ($wxtext) {
            $wxtext->delete();
            $keyword->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));

    }

    public function imgAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $wximg = WxImg::findBytoken($token);
        $this->view->setVar("wximg", $wximg);
    }

    public function addimgAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        if ($this->request->isPost() == true) {
            $wximg = new WxImg();
            $wximg->token = $token;
            $wximg->info = $this->request->getPost('editorValue');
            $wximg->click = 0;
            $wximg->createtime = date("Y-m-d H:i:s", strtotime("now"));
            $wximg->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($wximg->create($this->request->getPost())) {
                $this->flash->warning("保存成功");
                $keyword = new WxKeyword();
                $keyword->pid = $wximg->id;
                $keyword->token = $token;
                $keyword->module = "Img";
                $keyword->create($this->request->getPost());
            } else {
                $this->flash->warning("保存失败");
            }
        }
    }

    public function editimgAction($id)
    {
        if ($this->request->isPost() == true) {
            $wximg = WxImg::findFirstByid($id);
            $wximg->info = $this->request->getPost('editorValue');
            $wximg->updatetime = date("Y-m-d H:i:s", strtotime("now"));
            if ($wximg->update($this->request->getPost())) {
                $this->flash->warning("更新成功");
                $keyword = WxKeyword::findFirst("pid='" . $id . "' AND module='Img'");
                $keyword->update($this->request->getPost());
            } else {
                $this->flash->warning("更新失败");
            }
        }
        $wximg = WxImg::findFirstByid($id);
        $this->view->setVar("wximg", $wximg);
    }

    public function delimgAction($id)
    {
        $this->view->disable();
        $wximg = WxImg::findFirstByid($id);
        $keyword = WxKeyword::findFirst("module='Img' AND pid='" . $id . "'");
        if ($wximg) {
            $wximg->delete();
            $keyword->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));

    }

    public function wxmenuAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $menu = WxMenu::find("pid=0 AND token='" . $token . "'");
        $menu = $menu->toArray();
        foreach ($menu as $key => $vo) {
            $c = WxMenu::find("pid=" . $vo['id'] . " AND token='" . $token . "'");
            $menu[$key]['sub'] = $c->toArray();
        }
        $this->view->setVar("menu", $menu);
    }

    public function createmenuAction()
    {

        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        include $this->config->application->libDir . "wechat.class.php";
        $options = array(
            'token' => $wx->token, //填写你设定的key
            'appid' => $wx->appid, //填写高级调用功能的app id
            'appsecret' => $wx->appsecret, //填写高级调用功能的密钥
//            'encodingaeskey' => "de8GKSvzIhktR2xQsd3WQQeDNPL4Ylky8PrdKB31MFr", //填写加密用的EncodingAESKey
        );

        $weObj = new Wechat($options); //创建实例对象
        //TODO：调用$weObj各实例方法
//        $weObj->valid();//明文或兼容模式可以在接口验证通过后注释此句，但加密模式一定不能注释，否则会验证失败
        $nowmenu = $weObj->getMenu();
        print_r($nowmenu);
        //设置菜单
//            $newmenu = array(
//                "button" =>
//                    array(
//                        array('type' => 'click', 'name' => '最新消息', 'key' => 'MENU_KEY_NEWS'),
//                        array('type' => 'view', 'name' => '我要搜索', 'url' => 'http://www.qq.com'),
//                        array('type' => 'view', 'name' => '我要搜索', 'url' => 'http://www.sina.com'),
//                    )
//            );
        $menu = WxMenu::find("pid=0 AND token='" . $wx->token . "'");
        $menu = $menu->toArray();
        $rule = 0;
        foreach ($menu as $key => $vo) {
            if ($rule < 3) {
                if ($vo['url'] != "") {
                    $newmenu["button"][] = array('type' => 'view', 'name' => $vo['title'], 'url' => $vo['url']);
                } else {
                    $newmenu["button"][] = array('type' => 'click', 'name' => $vo['title'], 'key' => $vo['keyword']);
                }
                $c = WxMenu::find("pid=" . $vo['id'] . " AND token='" . $wx->token . "'");
                $rules = 0;
                foreach ($c->toArray() as $a => $i) {
                    if ($rules < 5) {
                        if ($i['url'] != "") {
                            $newmenu['button'][$key]['sub_button'][] = array('type' => 'view', 'name' => $i['title'], 'url' => $i['url']);
                        } else {
                            $newmenu['button'][$key]['sub_button'][] = array('type' => 'click', 'name' => $i['title'], 'key' => $i['keyword']);
                        }
                        $rules++;
                    } else
                        break;
                }
                $rule++;
            } else {
                break;
            }

        }
//
//        $newmenu = array(
//            "button" =>
//                array(
//                    array(
//                        'name' => '扫码',
//                        'sub_button' => array(
//                            0 => array(
//                                'type' => 'scancode_waitmsg',
//                                'name' => '扫码带提示',
//                                'key' => 'rselfmenu_0_0',
//                            ),
//                            1 => array(
//                                'type' => 'scancode_push',
//                                'name' => '扫码推事件',
//                                'key' => 'rselfmenu_0_1',
//                            ),
//                        ),
//                    ),
//                    array('type' => 'view', 'name' => '我要搜索', 'url' => 'http://www.qq.com'),
//                    array('type' => 'view', 'name' => '我要搜索', 'url' => 'http://www.baidu.com'),
//                )
//        );
        print_r($newmenu);

        $result = $weObj->createMenu($newmenu);
        if ($result) {
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));
    }

    public function addmenuAction($id)
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        if ($id) {
            if ($this->request->isPost() == true) {
                $menu = WxMenu::findFirstByid($id);
                if ($menu->update($this->request->getPost())) {
                    $this->flash->warning("更新成功");
                    $this->view->is_ok = true;
//                    $this->response->redirect("admin/appwx/wxmenu");
                } else {
                    foreach ($menu->getMessages() as $message) {
                        $this->flash->error((string)$message);
                    }
                }
            }
            $class = WxMenu::findFirstByid($id);
            $this->view->setVar("class", $class);
            $menu = WxMenu::find("pid=0 AND token='" . $token . "'");
            $this->view->setVar("menu", $menu);
        } else {
            if ($this->request->isPost() == true) {
                $menu = new WxMenu();
                $menu->token = $token;
                if ($menu->create($this->request->getPost())) {
                    $this->flash->warning("保存成功");
                    $this->view->is_ok = true;
                    //$this->response->redirect("admin/appwx/wxmenu");
                } else {
                    foreach ($menu->getMessages() as $message) {
                        $this->flash->error((string)$message);
                    }
                }
            }
            $menu = WxMenu::find("pid=0 AND token='" . $token . "'");
            $this->view->setVar("menu", $menu);
        }
    }

    public function delmenuAction($id)
    {
        $this->view->disable();
        $menu = WxMenu::findFirstByid($id);
        $submenu = WxMenu::findBypid($id);
        if ($menu) {
            $menu->delete();
            $submenu->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));

    }

    public function selectimgAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $wximg = WxImg::findBytoken($token);
        $this->view->setVar("wximg", $wximg);
    }

    public function multiAction()
    {
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        $imgmulit = WxImgmulti::findBytoken($token);
        $imgmulit = $imgmulit->toArray();
        foreach ($imgmulit as $key => $vo) {
            $id = explode(',', $vo['imgs']);
            foreach ($id as $k => $v) {
                $img = WxImg::findFirstByid($v);
                $title[$key][$v] = $img->title;
            }
            $imgmulit[$key]['title'] = $title[$key];
            //      print_r($imgmulit);
        }
        $this->view->setVar("imgs", $imgmulit);
    }

    public function addmultiAction()
    {
//        if ($this->request->isPost() == true) {
//            $status = 'error';
//         print($status);
//        }
        $Cuser = $this->Cuser;
        $wx = Wx::findFirstByuid($Cuser->uid);
        $token = $wx->token;
        if ($this->request->isPost() == true) {
            $this->view->disable();
            $imgmulti = new WxImgmulti();
            $imgmulti->keyword = $this->request->getPost("key");
            $imgmulti->imgs = $this->request->getPost("id_string");
            $imgmulti->token = $token;
            if ($imgmulti->create()) {
                $keyword = new WxKeyword();
                $keyword->pid = $imgmulti->id;
                $keyword->keyword = $imgmulti->keyword;
                $keyword->token = $token;
                $keyword->module = "Multi";
                $keyword->create($this->request->getPost());
                echo $this->json(1);
            } else {
                echo $this->json(0);
            }
        }

    }

    public function delmultiAction($id)
    {
        $this->view->disable();
        $wximgmulti = WxImgmulti::findFirstByid($id);
        $keyword = WxKeyword::findFirst("module='Multi' AND pid='" . $id . "'");
        if ($wximgmulti) {
            $wximgmulti->delete();
            $keyword->delete();
            $status = 'success';
        } else {
            $status = 'error';
        }
        return json_encode(array('status' => $status));
    }
}